import React, { useLayoutEffect, useState, useEffect } from 'react';
import { Select, Image } from 'antd';
import { MoonOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useSelector, useDispatch } from 'react-redux';
import { toggleTheme } from '../../store';

import { getState } from '@/api/common';
import "./index.scss"
import Logo from '@/static/images/logo.png';

function Header(props) {
  const isDark = useSelector(state => state.theme.isDark);
  // 获取 dispatch 函数
  const dispatch = useDispatch();
  const { t, i18n } = useTranslation();
  const [options, setOptions] = useState([
    {
      value: 'zh',
      label: '简体中文',
    },
    {
      value: 'en',
      label: 'English',
    },
    {
      value: 'jp',
      label: 'にほんご',
    }
  ]);
  const [value, setValue] = useState('zh');
  const [info, setInfo] = useState({});
  useLayoutEffect(() => {
    let language = localStorage.getItem('language') ? localStorage.getItem('language') : 'zh';
    setValue(language);
  }, [])
  function getLoad() {
    getState().then(res => {
      setInfo(res[0]);
    });
  }
  useEffect(() => {
    getLoad();
  }, [props.data]);
  function change(value) {
    localStorage.setItem('language', value);
    i18n.changeLanguage(value);
    setValue(value);
  }
  function theme() {
    dispatch(toggleTheme());
  }
  return (
    <>
      <div className="header">
        <div className="left">
          <div className="icon">
            <Image src={Logo} preview={false} />
          </div>
          <div className="title">
            {t('header.title')}
          </div>
        </div>
        <div className="right">
          <div className="status">
            <div className={"light " + info.state}>

            </div>
            <div className={'txt ' + info.state}>
              {info.state === 'on' ? (
                t('header.running')
              ) : info.state === 'off' ? (
                t('header.stopped')
              ) : (
                t('header.unknown')
              )}
            </div>
          </div>
          <div className="style" onClick={theme}>
            <div className="icon">
              <MoonOutlined style={{ fontSize: '12px' }} />
            </div>
            <div className="txt">
              {
                isDark ? t('header.lightMode') : t('header.darkMode')
              }
            </div>
          </div>
          <div className="language">
            <Select
              className='select'
              variant="borderless"
              value={value}
              style={{ width: 120, fontSize: '12px' }}
              options={options}
              onChange={change}
              getPopupContainer={triggerNode => triggerNode.parentElement}
            />
          </div>
        </div>
      </div>
    </>
  )
}

export default Header
